#!/usr/bin/env python3.9.2
# Date:2021/03/09
# Writed By Lemon 图片批处理工具
# -*- coding:utf-8 -*-

import os

from PIL import Image


def pictool(readfile):
    print(readfile)
    # 读取图片内容
    pic = Image.open(readfile)
    width, height = pic.size
    print("宽:", width, "高:", height)

    # 图片处理预判断 针对质量高图片操作 要求
    if width >= 750 and height >= 750:
        print("优质图片裁剪操作开始")

        # 图片宽大于高，以高为基准值，横图
        if width >= height:
            # 计算倍率，重定width,
            times = float('%.1f' % float(width / height))
            # print("缩放倍率", times)
            finalweight = times * 750
            # times_height = int(times * 1000)
            print("缩放倍率", finalweight)

            # 缩放至定高1000
            newp = pic.resize((int(finalweight), 750), Image.ANTIALIAS)

            # 设定裁切区域坐标计算
            x1 = (int(finalweight) - 750) // 2
            y1 = 0
            x2 = (int(finalweight) - 750) // 2 + 750
            y2 = 750
            box = (x1, y1, x2, y2)
            # print("裁切范围", x1, y1, x2, y2)
            newp = newp.crop(box)
            # 保存文件
            newp.save(file)

        # 图片宽小于高，以宽为基准值，竖图
        # 1500 2000
        if width < height:
            # 计算倍率，重定width
            times = float('%.1f' % float(height / width))
            print("缩放倍率", times)
            finalist = times * 750
            # print("缩放倍率", finalist)
            newp = pic.resize((750, int(finalist)), Image.ANTIALIAS)

            # 设定裁切区域坐标计算
            a1 = 0
            b1 = (int(finalist) - 750) // 2
            a2 = 750
            b2 = (int(finalist) - 750) // 2 + 750
            box = (a1, b1, a2, b2)
            # print("裁切范围", a1, b1, a2, b2)
            newp = newp.crop(box)
            newp.save(file)

    else:
        print(file + '图片不符合规范 不符合1000*1000最低要求不予处理')
    return


nowdir = os.getcwd()
print(nowdir)
os.chdir(nowdir + "\\image")
dirs = os.listdir(nowdir + "\\image")
imagedir = nowdir + "\\image"
count = 0
for file in dirs:
    pictool(file)
